package com.android.infantschool.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.infantschool.R;
import com.android.infantschool.bean.BaseBean;
import com.android.infantschool.bean.QiNiuTokenBean;
import com.android.infantschool.bean.ResponseBean;
import com.android.infantschool.manager.ThreadPoolManager;
import com.android.infantschool.model.config.AppCommand;
import com.android.infantschool.model.config.AppConfig;
import com.android.infantschool.model.http.OkHttpUtil;
import com.android.infantschool.model.mvp.presenter.PostHeaderPresenter;
import com.android.infantschool.model.mvp.presenter.PostHeaderPresenterImpl;
import com.android.infantschool.model.mvp.view.PostHeaderView;
import com.android.infantschool.model.qiniu.QnUploadHelper;
import com.android.infantschool.ui.imageloader.GlideRoundTransform;
import com.android.infantschool.util.Constant;
import com.android.infantschool.util.JsonGet;
import com.android.infantschool.util.ToastUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.qiniu.android.http.ResponseInfo;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author Administrator
 * @particulars
 * @time 2019\7\20 0020 18:39
 * @class describe
 */
public class PersonInfoActivity extends BaseActivity implements PostHeaderView {

    @BindView(R.id.img_back)
    public ImageView imgBack;
    @BindView(R.id.tv_title)
    public TextView tvTitle;
    @BindView(R.id.iv_header_photo)
    public ImageView ivHeaderPhoto;
    @BindView(R.id.tv_address)
    public TextView tvAddress;
    @BindView(R.id.title)
    public RelativeLayout rlTitle;
    @BindView(R.id.ly_header_photo)
    public RelativeLayout lyHeaderPhoto;
    @BindView(R.id.tv_name)
    public TextView tvName;
    @BindView(R.id.ly_name)
    public RelativeLayout lyName;
    @BindView(R.id.tv_send_word)
    public TextView tvSendWord;
    @BindView(R.id.ly_send_word)
    public RelativeLayout lySendWord;
    @BindView(R.id.ly_address)
    public RelativeLayout lyAddress;

    private int REQUEST_GET_IMAGE = 4;
    private PostHeaderPresenter headerPresenter = null;

    public static Intent newIntent(Activity activity) {
        Intent intent = new Intent(activity, PersonInfoActivity.class);
        return intent;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_persion_info);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        headerPresenter = new PostHeaderPresenterImpl(this);
        rlTitle.setPadding(0, this.height, 0, 0);
        tvTitle.setText("个人资料");
        tvName.setText(AppConfig.getNickName());

        Glide.with(this).load(AppConfig.getUserPhoto())
                .transform(new CenterCrop(this), new GlideRoundTransform(this))
                .into(ivHeaderPhoto);

    }

    @OnClick({R.id.img_back, R.id.ly_header_photo, R.id.ly_name, R.id.ly_send_word, R.id.ly_address})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                this.finish();
                break;
            case R.id.ly_header_photo:
                startCameta();
                break;
            case R.id.ly_name:
                //startActivityForResult(RenovatePersonInfoActivity.newIntent(this, 1, tvName.getText().toString()), 1);
                break;
            case R.id.ly_send_word:
                //startActivityForResult(RenovatePersonInfoActivity.newIntent(this, 2, tvSendWord.getText().toString()), 2);
                break;
            case R.id.ly_address:
                //startActivityForResult(RenovatePersonInfoActivity.newIntent(this, 3, tvAddress.getText().toString()), 3);
                break;
        }
    }

    /**
     * 跳转到相册页
     */
    private void startCameta() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        UUID uuid = UUID.randomUUID();
        File file = new File(Constant.IMAGE_PATH(), uuid.toString() + ".jpeg");//拍照文件的路径
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri uri = FileProvider.getUriForFile(this, "com.android.infantschool.fileprovider", file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        } else {
            Uri uri = Uri.fromFile(file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        startActivityForResult(intent, REQUEST_GET_IMAGE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_GET_IMAGE && resultCode == Activity.RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumns = {MediaStore.Images.Media.DATA};
            Cursor c = this.getContentResolver().query(selectedImage, filePathColumns, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePathColumns[0]);
            String picturePath = c.getString(columnIndex);
            Log.e(TAG, "图片路径:" + picturePath);

            this.showLoading();
            qiuNiuYunToKen(picturePath);
        }

        if (resultCode == 1 && null != data) {
            String content = data.getStringExtra("name");
            tvName.setText(content);
        }

        if (resultCode == 2 && null != data) {
            String content = data.getStringExtra("sendword");
            tvSendWord.setText(content);
        }

        if (resultCode == 3 && null != data) {
            String content = data.getStringExtra("address");
            tvAddress.setText(content);
        }
    }

    private Runnable runnable = null;

    /**
     * 上传到七牛
     *
     * @param picUrl
     */
    private void qiuNiuYunToKen(final String picUrl) {
        runnable = new Runnable() {
            @Override
            public void run() {
                String qiNiuToken = OkHttpUtil.getmInstance().postSync(AppCommand.QINIU_TOKEN, "token", AppConfig.getToken());
                Log.e(TAG, "qiNiuToken:" + qiNiuToken);
                if (qiNiuToken != null) {
                    QiNiuTokenBean tokenBean = null;
                    try {
                        tokenBean = JsonGet.getGson(qiNiuToken, new QiNiuTokenBean());
                    } catch (Exception e) {
                        Log.e(TAG, "e:" + e.toString());
                        tokenBean = null;
                    }
                    if (tokenBean == null) {
                        Log.e(TAG, "Token获取失败");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.showShortToast(PersonInfoActivity.this, "网络异常");
                            }
                        });
                        return;
                    }
                    if (tokenBean.getCode().equals("0")) {//Token获取成功
                        Log.e(TAG, "qiNiuToken:" + tokenBean.getData().getToken());
                        String ceshitoken = tokenBean.getData().getToken();//请求完接口获取到的token值
                        String key = tokenBean.getData().getKey();
                        Log.e(TAG, "++++++++ceshitoken:" + ceshitoken);
                        Log.e(TAG, "++++++picUrl=" + picUrl);
                        QnUploadHelper.uploadPic(picUrl, key, ceshitoken, new QnUploadHelper.UploadCallBack() {
                            @Override
                            public void success(String url) {
                                Log.e(TAG, "上传七牛成功:" + url);
                                Map<String, String> map = new HashMap<>();
                                map.put("serverToken", AppConfig.getToken());
                                map.put("url", url);
                                Log.e(TAG, "map:" + map.toString());
                                headerPresenter.postHeader(map);
                            }

                            @Override
                            public void fail(String key, final ResponseInfo info) {
                                Log.e(TAG, "上传失败:" + info.error);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        ToastUtil.showShortToast(PersonInfoActivity.this, "上传失败:" + info.error);
                                    }
                                });
                            }
                        });
                    } else {
                        Log.e(TAG, "Token获取失败:" + tokenBean.getMsg());
                        final QiNiuTokenBean finalTokenBean1 = tokenBean;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.showShortToast(PersonInfoActivity.this, "Token获取失败:" + finalTokenBean1.getMsg());
                            }
                        });
                    }
                } else {
                    Log.e(TAG, "接口异常或网络异常");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showShortToast(PersonInfoActivity.this, "网络或接口发生异常,请稍后再试");
                        }
                    });
                }
            }
        };
        ThreadPoolManager.getSingleInstance().execute(runnable);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (headerPresenter != null) {
            headerPresenter.onDestroy();
            headerPresenter = null;
        }
        if (runnable != null) {
            ThreadPoolManager.getSingleInstance().remove(runnable);
        }
    }

    @Override
    public void errorPostHeader(String error) {
        this.dismissLoading();
        ToastUtil.showShortToast(this, "网络异常:" + error);
    }

    @Override
    public void successPostHeader(BaseBean baseBean) {
        this.dismissLoading();
        ResponseBean responseBean = (ResponseBean) baseBean;
        if (responseBean.getCode() == 0) {
            AppConfig.setUserPhoto((String) responseBean.getData());
            ToastUtil.showShortToast(this, "更换成功");
            Glide.with(this).load(responseBean.getData())
                    .bitmapTransform(new GlideRoundTransform(this, 50))
                    .override(50, 50)
                    .into(ivHeaderPhoto);
        } else {
            ToastUtil.showShortToast(this, "更换失败:" + responseBean.getMsg());
        }
    }
}